<template>
  <div class="container">
    <div class="operation-bar">
      <el-button type="primary" @click="showImportDialog">导入</el-button>
      <el-button type="success" @click="handleDownload">下载</el-button>
    </div>

    <!-- 导入对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="文件导入"
      width="500px"
      @closed="resetForm"
    >
      <el-form
        ref="importFormRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="文件" prop="file">
          <el-upload
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleFileChange"
            accept="*/*"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">支持所有文件格式，大小不超过10MB</div>
              <div v-if="formData.file" class="file-name">
                已选文件：{{ formData.file.name }}
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入文件描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitImport" :loading="submitting"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 数据表格 -->
    <el-table
      :data="currentPageData"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" resizable />
      <el-table-column
        prop="name"
        label="文件名称"
        min-width="150"
        resizable
        show-overflow-tooltip
      />
      <el-table-column
        prop="storagePath"
        label="存储路径"
        min-width="250"
        resizable
        show-overflow-tooltip
      />
      <el-table-column
        prop="description"
        label="文件描述"
        min-width="200"
        resizable
        show-overflow-tooltip
      />
      <!-- <el-table-column prop="fileType" label="文件类型" width="120" /> -->
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next"
      :total="tableData.length"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import config from "@/config/index.js";
// 表格数据
const tableData = ref([]);
const selectedRows = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const { proxy } = getCurrentInstance();

// 对话框相关状态
const dialogVisible = ref(false);
const submitting = ref(false);
const importFormRef = ref(null);
const formData = ref({
  file: null,
  description: "",
});

onMounted(() => {
  getSimulationdatasList();
});

// 获取数据
const getSimulationdatasList = async () => {
  try {
    const data = await proxy.$api.getSimulationdatasList();
    tableData.value = data;
  } catch (error) {
    ElMessage.error("获取数据失败：" + error.message);
  }
};
// 表单验证规则
const formRules = {
  file: [{ required: true, message: "请选择上传文件", trigger: "change" }],
  description: [
    { required: true, message: "请输入文件描述", trigger: "blur" },
    { max: 200, message: "长度不能超过200个字符", trigger: "blur" },
  ],
};

// 分页计算
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

// 显示对话框
const showImportDialog = () => {
  dialogVisible.value = true;
};

// 处理文件选择
const handleFileChange = (uploadFile) => {
  formData.value.file = uploadFile.raw;
  importFormRef.value.validateField("file");
};

// 提交导入流程
const submitImport = async () => {
  try {
    // 表单验证
    const valid = await importFormRef.value.validate();
    if (!valid) return;

    submitting.value = true;

    // 第一步：上传文件获取路径
    const uploadForm = new FormData();
    uploadForm.append("file", formData.value.file);

    const uploadRes = await axios.post(
      "/api/simulationdatas/upload",
      uploadForm,
      {
        headers: {
          "Content-Type": "multipart/form-data",
          Accept: "*/*",
        },
      }
    );

    if (!uploadRes.data?.success) {
      throw new Error(uploadRes.data?.message || "文件上传失败");
    }
    const filePath = uploadRes.data.data.filePath;

    // 第二步：提交元数据
    const importParams = {
      name: formData.value.file.name,
      storagePath: filePath,
      description: formData.value.description,
      // fileType: formData.value.file.type || "未知类型",
    };

    const importRes = await axios.post("/api/simulationdatas", importParams);

    if (importRes.data?.success) {
      // 更新表格数据
      tableData.value.unshift({
        ...importParams,
        uploadTime: new Date().toLocaleString(),
      });

      ElMessage.success("导入成功");
      dialogVisible.value = false;
      getSimulationdatasList();
    } else {
      throw new Error(importRes.data?.message || "数据导入失败");
    }
  } catch (error) {
    console.error("导入失败:", error);
    ElMessage.error(`操作失败：${error.message}`);
  } finally {
    submitting.value = false;
  }
};

// 重置表单
const resetForm = () => {
  importFormRef.value.resetFields();
  formData.value.file = null;
};

// 下载处理
const handleDownload = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要下载的数据");
    return;
  }

  // 提取选中行的 ID 并拼接成逗号分隔的字符串
  const selectedIds = selectedRows.value.map((row) => row.id).join(",");

  try {
    // 构造下载链接
    const downloadUrl =  config.downloadUrl + `/simulationdatas/downloadSimulationDatasbyids?ids=${selectedIds}`;

    // 创建一个隐藏的 <a> 标签
    const link = document.createElement("a");
    link.href = downloadUrl;
    link.target = "_blank"; // 在新标签页中打开
    link.download = ""; // 如果后端返回了文件名，浏览器会自动处理
    document.body.appendChild(link);

    // 触发点击事件
    link.click();

    // 移除 <a> 标签
    document.body.removeChild(link);

    // ElMessage.success("下载已开始，请稍候");
  } catch (error) {
    console.error("下载失败:", error);
    ElMessage.error(`下载失败：${error.message}`);
  }
};

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}

.operation-bar .el-button {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.file-name {
  margin: 8px 0;
  color: #606266;
  font-size: 12px;
}

/* 调整表格样式 */
:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-table__header th) {
  background-color: #f5f7fa;
}

:deep(.el-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
